<template>
    <div class="game-panel">
        <div class="num-options">

            <div class="mushroom_box num" :class="{hover: hoverIndex == idx, knock: knockIndex == idx}" v-for="(num, idx) in numbers" :key="idx">
                <!-- 蘑菇头 -->
                <div class="mushroom_top" :style="{background: colors[idx]}">
                    <i></i>
                    <i></i>
                    <i :style="{color: colors[idx]}"><span class="value">{{ idx}}</span></i>
                    <i></i>
                    <i></i>
                    <div class="after" :style="{background: colors[idx]}"></div>
                </div>
                <!-- 蘑菇根部 -->
                <div class="mushroom_root"></div>
            </div>

        </div>
        <img :src="playerImage" class="player" ref="player" />
        
    </div>
</template>
<script>
  import xsImage01 from '@/assets/images/xs/01.png';
  import xsImage02 from '@/assets/images/xs/02.png';
  import xsImage03 from '@/assets/images/xs/03.png';
  import xsImage04 from '@/assets/images/xs/04.png';
  import xsImage05 from '@/assets/images/xs/05.png';
  import xsImage06 from '@/assets/images/xs/06.png';
  import xsImage07 from '@/assets/images/xs/07.png';
  import xsImage08 from '@/assets/images/xs/08.png';
  import xsImage09 from '@/assets/images/xs/09.png';
  import xsImage10 from '@/assets/images/xs/10.png';
  import xsImage11 from '@/assets/images/xs/11.png';
  import xsImage12 from '@/assets/images/xs/12.png';

export default {
    name: 'GamePanel',

    data(){
      return {
        numbers:[0,1,2,3,4,5,6,7,8,9],
        jumpLocked: false,
        appSize: {
            width : document.documentElement.clientWidth,
            height : document.documentElement.clientHeight
        },
        playerImages: [xsImage01, xsImage02, xsImage03, xsImage04, xsImage05, xsImage06, xsImage07, xsImage08, xsImage09, xsImage10, xsImage11, xsImage12],
        playerImageIndex: 0,
        colors: [],
        playerImage: xsImage01,
        player: {},
        knockIndex: null,
        inputValue: '',
        lastBackspaceTime: new Date().getTime(),
        lastJumpTime: new Date().getTime(),
        lastEnterTime: new Date().getTime(),
        lastAxisTime: new Date().getTime()
      }
    },
    mounted(){
        this.player = {
            element: this.$refs['player'],
            offset: {
                x:0,
                y:0
            },
            scale:{
                x: 1,
                y: 1
            }
        }
        for(let i = 0; i< 10; i++){
            this.colors.push(this.generateRandomColor());
        }


        this.playerInterval = setInterval(() => {
            
        }, 60);

        window.addEventListener("gamepadconnected", function(e) {
            console.log("Gamepad connected at index ", e.gamepad.index);
            
        });

        let that = this;
        function updateGamepad() {
            
            const gamepads = navigator.getGamepads();
            
            for (let gamepad of gamepads) {
                if (gamepad) {
                    // 读取按钮
                    for (let i = 0; i < gamepad.buttons.length; i++) {
                        let button = gamepad.buttons[i];
                        if (button.pressed) {
                            if(i == 0){ // A
                                that.arrowUp();
                            }
                            else if(i == 1){ // B
                                that.backspace();
                            }
                            else if(i == 2){ // X
                                that.gameover();
                            }
                            else if(i == 3){ // Y
                                that.enter();
                            }
                            //console.log(`Button ${i} pressed`);
                        }
                    }

                    // 读取轴
                    for (let i = 0; i < gamepad.axes.length; i++) {
                        if(i == 0){
                            let axis = gamepad.axes[i];
                            if(axis < -0.5){
                                that.arrowLeft();
                            }
                            else if(axis > 0.5){
                                that.arrowRight();
                            }
                        }

                    }
                }
            }

            requestAnimationFrame(updateGamepad);
        }

        // 启动轮询
        requestAnimationFrame(updateGamepad);

        document.addEventListener("keydown", (e)=> {
            let code = e.code;
            if(code == 'ArrowLeft'){
                this.arrowLeft();
            }
            else if(code == 'ArrowRight'){
                this.arrowRight();
            }
            else if(code == 'ArrowUp'){
                this.arrowUp();
            }
            else if(code == 'ArrowDown'){
                this.arrowDown();
            }
            else if(code == 'Enter'){
                this.enter();
            }
            else if(code == 'Backspace'){
                this.backspace();
            }
            
            //console.log(code);
        })

    },
    beforeDestroy(){
        
    },
    watch: {
        '$store.state.app.appSize':{
            handler(val){
                if(val){
                    
                    this.appSize = {
                        width : val.width,
                        height : val.height
                    }
                }
                
            },
            immediate: true
        }
    },
    computed:{
        hoverIndex(){
            let offset = this.player.offset || {x:0,y:0};
            let v = offset.x / 180;
            let d = Math.abs(v % 1);
            if(d < 0.2 || d > 0.8){
                return null;
            }
            
            let index = Math.floor(v  + 5);
            return index;
        }
        
    },
    methods:{
        changePlayerImage(){
            this.playerImageIndex = ++this.playerImageIndex % this.playerImages.length ;
            this.playerImage = this.playerImages[this.playerImageIndex];
        },
        generateRandomColor() {
            let r = Math.floor(Math.random() * 255);
            let g = Math.floor(Math.random() * 255);
            let b = Math.floor(Math.random() * 255);
            let color = "rgba(" + r + "," + g + "," + b + "," + 1 + ")";
            return color;
        },

        arrowUp(){
            if(this.jumpLocked){
                return ;
            }
            this.jumpLocked = true;
            let d = 60;
            let startY = this.player.offset.y;
            let step = 1;
            let interval = setInterval(() => {
            let offset = this.player.offset;
            let y = this.player.offset.y - step * 6;
            if(Math.abs(y - startY) >= d){
                this.knockIndex = this.hoverIndex;
                setTimeout(() => {
                    this.knockIndex = null;
                }, 1200);
                step = -1;
            }
            this.player.offset.y = y;
            
            this.player.element.style.transform = `translate(${offset.x}px, ${offset.y}px) scale(${this.player.scale.x}, ${this.player.scale.y})`;
            
            if(offset.y == startY && step == -1){
                clearInterval(interval);
                this.jumpLocked = false;
                if(this.hoverIndex !== null){
                    let number = this.numbers[this.hoverIndex];
                    if(number !== undefined){
                        this.inputValue += this.numbers[this.hoverIndex].toString();
                        this.$emit('input', this.inputValue);
                    }    
                }
                
            }

            }, 16);
            
        },
        arrowDown(){
            return ;
        },
        arrowLeft(){
            this.player.scale.x = -1;
            if(this.jumpLocked){
                return ;
            }
            let offset = this.player.offset;
            if(offset.x < -860){
                offset.x = 860;
            }
            else{
                offset.x -= 20;
            }
            this.player.element.style.transform = `translate(${offset.x}px, ${offset.y}px) scale(${this.player.scale.x}, ${this.player.scale.y})`;
            this.changePlayerImage();
        },
        
        arrowRight(){
            this.player.scale.x = 1;
            if(this.jumpLocked){
                return ;
            }
            let offset = this.player.offset;
            if(offset.x > 860){
                offset.x = -860;
            }
            else{
                offset.x += 20;
            }
            
            this.player.element.style.transform = `translate(${offset.x}px, ${offset.y}px) scale(${this.player.scale.x}, ${this.player.scale.y})`;
            this.changePlayerImage();
        },
        gameover(){
           this.$emit('gameover')  
        },
        enter(){
            let timestamp = this.getTimestamp();
            if(timestamp - this.lastEnterTime < 200){
                return ;
            }
            this.lastEnterTime = timestamp;
            if(this.inputValue === ''){
                return ;
            }
            this.$emit('enter', this.inputValue);
            this.inputValue = '';
        },
        backspace(){
            let timestamp = this.getTimestamp();
            if(timestamp - this.lastBackspaceTime < 200){
                return ;
            }
            this.lastBackspaceTime = timestamp;
            if(this.inputValue.length == 0){
                return ;
            }
            //console.log(this.inputValue);
            this.inputValue = this.inputValue.substring(0, this.inputValue.length - 1);
            this.$emit('input', this.inputValue);
        },
        getTimestamp(){
            return new Date().getTime();
        }
      
    }
   
  }
  </script>
  
  <style scoped>
   
    .game-panel{
        border-bottom: 1px solid rgba(20, 20, 20, 0.2);
    }
    .num-options{
        margin: 0 auto;
        width: 1800px;
        display: flex;
        justify-content: center;
        .num{
            cursor: pointer;
        }
        
    }

    .player{
        width: 144px;
        height: 144px;
        margin-right: 80px;
        transform-origin: 110px center;
    }

    .mushroom_box {
        position: relative;
        box-sizing: border-box;
        width: 204px;
        margin: 0 auto;
        display: flex;
        flex-direction: column;
        align-items: center;
        opacity: 0.5;

        &.hover{
            opacity: 1;
        }

        .mushroom_top {
            position: relative;
            width: 170px;
            height: 90px;
            background: #FE876F;
            border-top-left-radius: 100px;
            border-top-right-radius: 100px;
            border: 2px solid #000;
            
        }

        .mushroom_top .after {
            position: absolute;
            top:  calc(100% - 4px);
            width: 170px;
            height: 40px;
            border-bottom-left-radius: 100px;
            border-bottom-right-radius: 100px;
            background: #FE876F;
    
            left: -2px;
            border: 2px solid #000;
            border-top: none;
        }

        .mushroom_root {
            width: 60px;
            height: 60px;
            background: #FFF6E5;
            border: 2px solid #000;
            border-top-left-radius: 75px;
            border-top-right-radius: 75px;
            border-bottom-left-radius: 50px;
            border-bottom-right-radius: 50px;
        }

        .mushroom_top>i {
            
            position: absolute;
            width: 25px;
            height: 25px;
            border-radius: 50%;
            background: #FFF9D6;
            border: 3px solid #000;
            top: 10%;
            left: 35%;
            font-size: 60px;
            color:#FE876F;
            font-family:'Courier New', Courier, monospace;
            line-height: 60px;
            text-align: center;
            font-style: normal;
            font-weight: bold;
            text-shadow: -2px -2px 0 #000, 2px -2px 0 #000, -2px 2px 0 #000, 2px 2px 0 #000;
            
        }
        
        .mushroom_top>i:nth-child(2) {
            top: 30%;
            left: 20%;
            width: 20px;
            height: 25px;
            transform: skew(20deg, 20deg);
        }
        
        .mushroom_top>i:nth-child(3) {
            top: 56%;
            left: 32%;
            width: 60px;
            height: 60px;
            z-index: 8;
            
        }
        
        .mushroom_top>i:nth-child(4) {
            top: 70%;
            left: 1%;
            width: 30px;
            height: 30px;
            transform: skew(0deg, -10deg);
            z-index: 8;
        }
        
        .mushroom_top>i:nth-child(5) {
            top: 35%;
            left: 70%;
            width: 40px;
            height: 45px;
            z-index: 8;
            transform: skew(0deg, 20deg);
        }
    }

    .knock{
        animation: knock 1s ease 1;

        .value{
            display: block;
            animation: knock_inner 0.2s linear 5;
        }
    }

    @keyframes knock_inner {
        0% {
            transform: scale(2) rotateY(0);
        }
        50% {
            transform: scale(2) rotateY(180deg);
        }
        100% {
            transform: scale(2) rotateY(360deg);
        }
    }

    @keyframes knock {
        0% {
            transform: rotate(0deg);
        }
        10% {
            transform: rotate(0deg) translateY(-5px);
        }
        
        15% {
            transform: rotate(0deg) translateY(-25px);
        }
        20%{
            transform: rotate(10deg) translateY(-20px);
        }
        25%{
            transform: rotate(0deg) translateY(-25px);
        }
        30%{
            transform: rotate(-10deg) translateY(-20px);
        }
        35%{
            transform: rotate(0deg) translateY(-25px);
        }

        40% {
            transform: rotate(0deg) translateY(-25px);
        }
        45%{
            transform: rotate(10deg) translateY(-20px);
        }
        50%{
            transform: rotate(0deg) translateY(-25px);
        }
        55%{
            transform: rotate(-10deg) translateY(-20px);
        }
        60%{
            transform: rotate(0deg) translateY(-25px);
        }


        65% {
            transform: rotate(0deg) translateY(-25px);
        }
        70%{
            transform: rotate(10deg) translateY(-20px);
        }
        75%{
            transform: rotate(0deg) translateY(-25px);
        }
        80%{
            transform: rotate(-10deg) translateY(-20px);
        }
        85%{
            transform: rotate(0deg) translateY(-25px);
        }



        90% {
            transform: rotate(0deg) translateY(-5px);
        }
        100% {
            transform: rotate(0deg);
        }
    }
    
    
    

    
  </style>
  